﻿using System;
using System.IO;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Saisie_des_prélèvements.Models;
using Saisie_des_prélèvements.Views;
using Saisie_des_prélèvements.Common;
using System.Threading.Tasks;
using Windows.Storage;

// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227

namespace Saisie_des_prélèvements
{
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    sealed partial class App : Application
    {
        public static string DBPath = string.Empty;
        public static int CurrentUserId { get; set; }
        public static string Marchine = string.Empty;
        public static string AppUri = string.Empty;
        public static string Client = string.Empty;
        public static int? ClientTakenId;
        public static int ZoneIndex;
        private string DataSample = string.Empty;

        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;
        }

        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used when the application is launched to open a specific file, to display
        /// search results, and so forth.
        /// </summary>
        /// <param name="args">Details about the launch request and process.</param>
        protected async override void OnLaunched(LaunchActivatedEventArgs args)
        {
            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                await CreateIfNotExists("config.txt");
                await ReadConfig();
                if (DataSample == "1")
                    await CreateIfNotExists("CetT_paster.s3db");

                // Get a reference to the SQLite database
                DBPath = Path.Combine(
                    //Windows.ApplicationModel.Package.Current.InstalledLocation.Path, "kalfi_paster.s3db");
                    Windows.Storage.ApplicationData.Current.LocalFolder.Path, "CetT_paster.s3db");
                // Initialize the database if necessary
                using (var db = new SQLite.SQLiteConnection(DBPath))
                {
                    // Create the tables if they don't exist
                    db.CreateTable<k_contract_h>();
                    db.CreateTable<k_taken_h>();
                    db.CreateTable<k_taken_analyze_h>();
                    db.CreateTable<k_client_taken>();
                    db.CreateTable<k_contract>();
                    db.CreateTable<k_system_parameter>();
                    db.CreateTable<k_taken>();
                    db.CreateTable<k_taken_analyze>();
                    db.CreateTable<k_user>();
                    db.CreateTable<k_setting>();
                    db.CreateTable<k_zone_geographic>();
                    db.CreateTable<k_export>();
                    db.CreateTable<k_export_client>();
                    db.CreateTable<NTIERS_X>();
                    db.CreateTable<NPRODUIT>();
                    db.CreateTable<PLANCONT>();
                    db.CreateTable<SECTEURS>();
                    db.CreateTable<ANALYSES>();
                    db.CreateTable<ANAPLAN>();
                    db.CreateTable<ANAPRD>();
                    db.CreateTable<IDENT01>();
                    db.CreateTable<IDENT02>();
                    db.CreateTable<IDENT03>();
                    db.CreateTable<IDENT04>();
                    db.CreateTable<IDENT05>();
                    db.CreateTable<IDENT06>();
                    db.CreateTable<IDENT07>();
                    db.CreateTable<IDENT08>();
                    db.CreateTable<IDENT09>();
                    db.CreateTable<IDENT10>();
                    db.CreateTable<IDENT11>();
                    db.CreateTable<IDENT12>();
                    db.CreateTable<PTPREL>();
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                if (!rootFrame.Navigate(typeof(LoginPage), args.Arguments))
                {
                    throw new Exception("Failed to create initial page");
                }
            }
            // Ensure the current window is active
            Window.Current.Activate();
        }

        private async Task CreateIfNotExists(string dbName)
        {
            if (await GetIfFileExistsAsync(dbName) == null)
            {

                StorageFile seedFile = await StorageFile.GetFileFromPathAsync(
                Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path,
                dbName));
                await seedFile.CopyAsync(Windows.Storage.ApplicationData.Current.LocalFolder);
            }
        }

        private async Task<StorageFile> GetIfFileExistsAsync(string key)
        {
            try
            {
                return await ApplicationData.Current.LocalFolder.GetFileAsync(key);
            }
            catch (FileNotFoundException) { return default(StorageFile); }
        }

        private async Task ReadConfig()
        {
            var path = "config.txt";
            var folder = Windows.Storage.ApplicationData.Current.LocalFolder;
            try
            {
                Windows.Storage.StorageFile file = await folder.GetFileAsync(path);
                var readFile = await Windows.Storage.FileIO.ReadLinesAsync(file);
                foreach (var line in readFile)
                {
                    if (line.Split('=')[0].ToLower() == "id")
                        App.Marchine = line.Split('=')[1];
                    else if (line.Split('=')[0].ToLower() == "server")
                        App.AppUri = string.Format("{0}{1}", line.Split('=')[1], "kalficom/");
                    else if (line.Split('=')[0].ToLower() == "client")
                        App.Client = line.Split('=')[1];
                    else if (line.Split('=')[0].ToLower() == "sample")
                        DataSample = line.Split('=')[1];
                }
            }
            catch (FileNotFoundException f)
            {

            }
        }

        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        private void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();
            //TODO: Save application state and stop any background activity
            deferral.Complete();
        }
    }
}
